package com.suixun.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.authority.common.UserTypeEnum;
import com.authority.controller.BaseManager;
import com.google.gson.Gson;
import com.suixun.entity.StatDeviceInfo;
import com.suixun.entity.form.ParamForm;
import com.suixun.exception.OpServiceException;
import com.suixun.service.WorkspaceService;
import com.suixun.util.Constant;
import com.suixun.util.DateUtil;
import com.suixun.vo.WorkSpaceVO;

/**
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/workspaceManager")
public class WorkspaceManage extends BaseManager {
	@Resource
	private WorkspaceService workspaceService;

	/**
	 * 统计所有设备
	 * 
	 * @return
	 */

	@RequestMapping(value = "statDeviceList.json")
	@ResponseBody
	public Object statDeviceList(String param) {
		boolean bln=checkRight();
		if(!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		try {
			ParamForm paramForm = checkParam(param, ParamForm.class);
			if (getUserType(getUserId()) == UserTypeEnum.REGIONMAN.getType()) {
				paramForm.setUserid(getUserId());
			}
			if(paramForm!=null && paramForm.getEnddate()!=null && !paramForm.getEnddate().trim().equals("")) {
				paramForm.setEnddate(paramForm.getEnddate()+" 23:59:59");
			}
			return success(workspaceService.statTotalDevice(paramForm));
		} catch (Exception e) {
			e.printStackTrace();
			logger("WorkspaceManage statDeviceList:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}
	
	/**
	 * 按日期统计所有设备
	 * 
	 * @return
	 */

	@RequestMapping(value = "statDeviceListByDate.json")
	@ResponseBody
	public Object statDeviceListByDate(String param) {
		boolean bln=checkRight();
		if(!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		ParamForm paramForm = new ParamForm();
		try {
			Date startDate=null;
			Date endDate=null;
			if (getUserType(getUserId()) == UserTypeEnum.REGIONMAN.getType()) {
				paramForm.setUserid(getUserId());
			}
			//缺省统计最近7天的数据
			if(param!=null)
			{
				paramForm = new Gson().fromJson(param, ParamForm.class);
				if(paramForm.getStartdate()!=null && !paramForm.getStartdate().trim().equals(""))
					startDate=new SimpleDateFormat("yyyy-MM-dd").parse(paramForm.getStartdate().trim());
				if(paramForm.getEnddate()!=null && !paramForm.getEnddate().trim().equals(""))
					endDate=new SimpleDateFormat("yyyy-MM-dd").parse(paramForm.getEnddate().trim());
			}
			if(endDate==null)
			{
				if(startDate==null)
					endDate=new Date();
				else
				{
					endDate=(Date)startDate.clone();
					endDate.setDate(endDate.getDate()+6);
				}
			}
			if(startDate==null)
			{
				startDate=(Date)endDate.clone();
				startDate.setDate(startDate.getDate()-6);
			}
			paramForm.setStartdate(DateUtil.formatDateToString(startDate, "yyyy-MM-dd"));
			paramForm.setEnddate(DateUtil.formatDateToString(endDate, "yyyy-MM-dd")+" 23:59:59");
			
			LinkedHashMap<String,StatDeviceInfo> intelligentMap=new LinkedHashMap<String,StatDeviceInfo>();
			LinkedHashMap<String,StatDeviceInfo> cardMap=new LinkedHashMap<String,StatDeviceInfo>();
			LinkedHashMap<String,StatDeviceInfo> card2Map=new LinkedHashMap<String,StatDeviceInfo>();
			LinkedHashMap<String,StatDeviceInfo> payMap=new LinkedHashMap<String,StatDeviceInfo>();
			while(!startDate.after(endDate))
			{
				String statDate=DateUtil.formatDateToString(startDate, "MM/dd");
				StatDeviceInfo intelligentInfo=new StatDeviceInfo();
				intelligentInfo.setStatdate(statDate);
				intelligentInfo.setDevicetype(2);
				intelligentMap.put(statDate,intelligentInfo);
				
				StatDeviceInfo cardInfo=new StatDeviceInfo();
				cardInfo.setStatdate(statDate);
				cardInfo.setDevicetype(24);
				cardMap.put(statDate,cardInfo);
				
				StatDeviceInfo card2Info=new StatDeviceInfo();
				card2Info.setStatdate(statDate);
				card2Info.setDevicetype(1356);
				card2Map.put(statDate,card2Info);
				
				StatDeviceInfo payInfo=new StatDeviceInfo();
				payInfo.setStatdate(statDate);
				payInfo.setDevicetype(1);
				payMap.put(statDate,payInfo);
				startDate.setDate(startDate.getDate()+1);
			}
			
			
			
			List<StatDeviceInfo> list=workspaceService.statTotalDeviceByDate(paramForm);
			for(int i=0;i<list.size();i++)
			{
				StatDeviceInfo info=list.get(i);
				if(info.getDevicetype()!=null && info.getDevicetype()==2 && intelligentMap.get(info.getStatdate())!=null)
				{
					intelligentMap.get(info.getStatdate()).setValidcounts(info.getValidcounts());
				}
				if(info.getDevicetype()!=null && "24".equals(String.valueOf(info.getDevicetype())) && cardMap.get(info.getStatdate())!=null)
				{
					cardMap.get(info.getStatdate()).setValidcounts(info.getValidcounts());
				}
				if(info.getDevicetype()!=null && "1356".equals(String.valueOf(info.getDevicetype())) && cardMap.get(info.getStatdate())!=null)
				{
					card2Map.get(info.getStatdate()).setValidcounts(info.getValidcounts());
				}
			}
			list=workspaceService.statPaylistByDate(paramForm);
			for(int i=0;i<list.size();i++)
			{
				StatDeviceInfo info=list.get(i);
				if(info.getDevicetype()!=null && info.getDevicetype()==2 && payMap.get(info.getStatdate())!=null)
				{
					payMap.get(info.getStatdate()).setPaycounts(info.getPaycounts());
				}
				if(info.getDevicetype()!=null && "24".equals(String.valueOf(info.getDevicetype())) && cardMap.get(info.getStatdate())!=null)
				{
					payMap.get(info.getStatdate()).setPaycounts(info.getPaycounts());
				}
				if(info.getDevicetype()!=null && "1356".equals(String.valueOf(info.getDevicetype())) && cardMap.get(info.getStatdate())!=null)
				{
					payMap.get(info.getStatdate()).setPaycounts(info.getPaycounts());
				}
			}
			
			List<LinkedHashMap> result=new LinkedList<LinkedHashMap>();
			result.add(intelligentMap);
			result.add(cardMap);
			result.add(payMap);
			result.add(card2Map);
			
			return success(result);
		} catch (Exception e) {
			logger("WorkspaceManage statDeviceListByDate:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}
	
	/**
	 * 获取地区统计列表
	 * 
	 * @return
	 */

	@RequestMapping(value = "/countByRegion.json")
	@ResponseBody
	public Object countByRegion(String param) {
		boolean bln=checkRight();
		if(!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if(param==null) {
			return fail(Constant.EMPTY);
		}
		try {
			ParamForm paramForm = new Gson().fromJson(param, ParamForm.class);
			if (getUserType(getUserId()) == UserTypeEnum.REGIONMAN.getType()) {
				paramForm.setUserid(getUserId());
			}
			if(paramForm == null || StringUtil.isBlank(paramForm.getProvince())) {
				return fail(Constant.WorkSpace.REGION_NOT_NULL);
			}
			return success(workspaceService.getcountByRegion(paramForm));
		} catch (Exception e) {
			logger("WorkspaceManage countByRegion:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}
	
	/**
	 * 获取学校统计详情
	 * 
	 * @return
	 */

	@RequestMapping(value = "/countBySchool.json")
	@ResponseBody
	public Object countBySchool(String param) {
		boolean bln=checkRight();
		if(!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if(param==null) {
			return fail(Constant.WorkSpace.SCHOOL_NOT_NULL);
		}
		try {
			ParamForm paramForm = new Gson().fromJson(param, ParamForm.class);
			if (getUserType(getUserId()) == UserTypeEnum.REGIONMAN.getType()) {
				paramForm.setUserid(getUserId());
			}
			if(paramForm == null || StringUtil.isBlank(paramForm.getSchoolname())) {
				return fail(Constant.WorkSpace.SCHOOL_NOT_NULL);
			}
			return success(workspaceService.getClassCountsBySchool(paramForm));
		} catch (Exception e) {
			e.printStackTrace();
			if (e instanceof OpServiceException) {
				return fail(e);
			}
			logger("WorkspaceManage countBySchool:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}
	
	/**
	 * 导出excel
	 * 
	 * @return
	 */

	@RequestMapping(value = "/export_countByRegion.json")
	@ResponseBody
	public Object exportCountByRegion(String param) {
		boolean bln=checkRight();
		if(!bln) {
			toRedirect(404);
		}
		if(param==null) {
			toRedirect(500);
		}
		
		try {
			ParamForm paramForm = new Gson().fromJson(param, ParamForm.class);
			if (getUserType(getUserId()) == UserTypeEnum.REGIONMAN.getType()) {
				paramForm.setUserid(getUserId());
			}
			if(paramForm == null || StringUtil.isBlank(paramForm.getProvince())) {
				toRedirect(500);
			}
			ArrayList<String> listParm = new ArrayList<String>();
			listParm.add("省");
			listParm.add("市");
			listParm.add("区");
			listParm.add("学校名称");
			listParm.add("促销时间");
			listParm.add("考勤卡类型");
			listParm.add("考勤卡发放量");
			listParm.add("考勤卡激活量");
			listParm.add("学生证发放量");
			listParm.add("学生证激活量");
			listParm.add("学生证缴费量");
			List<List<String>> listValue=new LinkedList<List<String>>();
			//限制最多导出1万条数据，前端可以通过细化查询条件来多次导出
			if(StringUtil.isBlank(paramForm.getPagecount()))
				paramForm.setPagecount(Constant.Excel.EXPORT_ROWS);
			List<WorkSpaceVO> list = workspaceService.getcountByRegion(paramForm);
			
			//限制最多导出1万条数据，前端可以通过细化查询条件来多次导出
			for (int m = 0; m < list.size(); m++) {
				List<String> value=new LinkedList<String>();
				WorkSpaceVO workSpaceVo = list.get(m);
				value.add(workSpaceVo.getProvince());
				value.add(workSpaceVo.getCity());
				value.add(workSpaceVo.getTown());
				value.add(workSpaceVo.getSchoolname());
				value.add(workSpaceVo.getDiscounttime());
				value.add(workSpaceVo.getDevicetypename());
				value.add(String.valueOf(workSpaceVo.getCardsendcounts()));
				value.add(String.valueOf(workSpaceVo.getCardvalidcounts()));
				value.add(String.valueOf(workSpaceVo.getDevicesendcounts()));
				value.add(String.valueOf(workSpaceVo.getDevicevalidcounts()));
				value.add(String.valueOf(workSpaceVo.getDevicepaycounts()));
				listValue.add(value);
			}
			
			// 创建新的Excel 工作簿
			HSSFWorkbook workbook = exportDeviceList("学校统计表",listParm,listValue);
			HttpServletResponse response=this.getResponse();
			response.setHeader("Content-disposition", "attachment;filename=schoolcounts.xls");
			workbook.write(this.getResponse().getOutputStream());
			workbook.close();
		} catch (Exception e) {
			logger("WorkspaceManage exportCountByRegion:"+e.getMessage(),e);
			toRedirect(500);
		}
		return success();

	}
	
}
